package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-26
 */
@Service
@RequiredArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{

    private final CheckInMapper checkInMapper;
    private final ElderServiceImpl elderService;
    private final BedMapper bedMapper;
    private final CheckInConfigMapper checkInConfigMapper;
    private final ContractMapper contractMapper;

    public final static int Bed_Status=1;
    private final ElderMapper elderMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //查询入住信息
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        if (checkIn == null){
            throw  new BaseException("老人为入住");
        }
        //查询老人信息
        Elder elder = elderMapper.selectElderById(Long.valueOf(checkIn.getElderId()));
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        //计算年龄
        LocalDate birthDay = LocalDate.parse(elder.getBirthday());
        checkInElderVo.setAge(LocalDateTime.now().getYear()-birthDay.getYear());
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //查询家属信息
        if (StringUtils.hasText(checkIn.getRemark())){
            List<ElderFamilyVo> elderFamilyVoList  = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        }else{
            checkInDetailVo.setElderFamilyVoList(new ArrayList<>());
        }
        //查询入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigById(id);
//        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        //设置入住开始结束时间，测试发现没有回显才知道这里需要单独设置的
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //查询合同
          //   Contract contract = contractMapper.selectContractById(Long.valueOf(elder.getId()));
        // 使用 elder.getId() 作为 elder_id 去查询合同
        Contract contract = contractMapper.selectOne(
                Wrappers.<Contract>lambdaQuery()
                        .eq(Contract::getElderId, Long.valueOf(elder.getId()))
        );
        //     Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, Long.valueOf(checkIn.getElderId())));

        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }



    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkInApplyDto 入住
     * @return 结果
     */
    @Override
    @Transactional
    public void applyCheckIn(CheckInApplyDto checkInApplyDto)
    {   //查询老人  通过身份证号查询
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo());
        Elder elder = elderService.getOne(wrapper);
        if (elder !=null && elder.getStatus()==1){
            throw new BaseException("老人已入住");
        }
        //更新床位的状态  已入住
        Bed bed=bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(Bed_Status);
        bedMapper.updateBed(bed);
        //新增老人
        elder = insertEleder(bed,checkInApplyDto.getCheckInElderDto());
        //新增入住信息
        CheckIn checkIn = insertCheckIn(elder,checkInApplyDto);
        //新增入住配置信息
        insertCheckInConfig(checkIn.getId(),checkInApplyDto);
        //新增签约信息
        insertContract(elder,checkInApplyDto);
    }
    /**
     * 新增合同
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
    String contractNo="HT"+ CodeGenerator.generateContractNumber();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId());
        contract.setContractNumber(contractNo);
        contract.setContractName(elder.getName());
        contract.setElderName(elder.getName());
        //状态、开始时间、结束时间
        //签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime  = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isAfter(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    /**
     * 新增入住配置
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInApplyDto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        //家人信息
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setBedNumber(elder.getBedNumber());
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增老人
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertEleder(Bed bed, CheckInElderDto checkInElderDto) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elderService.save(elder);
        return elder;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

}
